// @ts-ignore
import IpcMain = Electron.IpcMain
import { Connection, QueryResult } from './type'
import type { Result } from '@tdengine/rest'

const { options, connect } = require('@tdengine/rest')

let currConnection: Connection
let currDatabase: string
async function changeConnection(connection: Connection): Promise<boolean> {
  return new Promise<boolean>((resolve) => {
    currConnection = connection
    console.log('change connection: ', connection)
    resolve(true)
  })
}

async function changeDatabase(database: string): Promise<boolean> {
  return new Promise<boolean>((resolve) => {
    currDatabase = database
    console.log('change database: ', database)
    resolve(true)
  })
}

async function getCurrConnection(): Promise<string> {
  return new Promise<string>((resolve) => {
    console.log('get curr connection: ', currConnection)
    resolve(JSON.stringify(currConnection))
  })
}

async function getCurrDatabase(): Promise<string> {
  return new Promise<string>((resolve) => {
    console.log('get curr database: ', currDatabase)
    resolve(currDatabase)
  })
}

async function doQuery(sql: string): Promise<QueryResult> {
  return new Promise<QueryResult>((resolve) => {
    console.log('query sql: ', sql)

    const queryResult = new QueryResult(false)

    options.path = '/rest/sql' + (currDatabase ? '/' + currDatabase : '')
    options.host = currConnection.host
    options.port = currConnection.port
    options.user = currConnection.username
    options.passwd = currConnection.password
    const tdConnect = connect(options)

    tdConnect
      .cursor()
      .query(sql)
      .then((result: Result) => {
        const errCode = result.getErrCode()
        queryResult.success = errCode !== undefined && errCode == 0
        queryResult.message = result.getErrStr()
        queryResult.meta = result.getMeta()
        queryResult.data = result.getData()
      })
      .finally(() => {
        resolve(queryResult)
      })
  })
}

export function register(ipcMain: IpcMain) {
  // @ts-ignore
  ipcMain.handle('changeConnection', function (event, connection) {
    return changeConnection(JSON.parse(connection))
  })
  // @ts-ignore
  ipcMain.handle('changeDatabase', function (event, database) {
    return changeDatabase(database)
  })
  // @ts-ignore
  ipcMain.handle('doQuery', function (event, sql) {
    return doQuery(sql)
  })
  // @ts-ignore
  ipcMain.handle('getCurrConnection', function (event) {
    return getCurrConnection()
  })
  // @ts-ignore
  ipcMain.handle('getCurrDatabase', function (event) {
    return getCurrDatabase()
  })
}
